// 登录请求
import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken, setTokenTime } from '@/utils/auth.js'
// 清空路由规则
import { resetRouter, constantRoutes } from '@/router/index'
// user模板数据
const state = {
  // 获取token
  token: getToken(),
  // 用户信息
  userInfo: {},
  menus: [],
  points: {
    ponitDelete: 'point-user-delete',
    ponitAdd: 'point-user-add',
    ponitUpdate: 'point-user-update'
  }
}
const mutations = {
  // 获取token
  setToken(state, payload) {
    state.token = payload
    // 保存token
    setToken(payload)
  },
  // 保存用户信息
  setuserInfo(state, payload) {
    state.userInfo = payload
  },
  // 删除token
  romoveToken(state) {
    state.token = null
    removeToken()
  },
  // 删除用户信息
  romoveUserInfo(state) {
    state.userInfo = {}
  },
  // 用户退出登录
  logout() {
    this.commit('user/romoveToken')
    this.commit('user/romoveUserInfo')
    this.commit('user/setMenus', [])
    // 清空路由规则
    resetRouter()
  },
  // 渲染左侧菜单
  setMenus(state, payload) {
    state.menus = [...constantRoutes, ...payload]
  }
}
const actions = {
  // 登录请求
  async login(context, data) {
    const res = await login(data)
    context.commit('setToken', res)
    setTokenTime()
  },
  // 获取用户信息
  async getUserInfo(context) {
    const userInfo = await getUserInfo()
    const userDetail = await getUserDetailById(userInfo.userId)
    context.commit('setuserInfo', { ...userInfo, ...userDetail })
    return userInfo
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

